/* Copyright (c) 2007 杭州奇峰信息技术有限公司.
 *
 * 该源代码版权归本公司所有。
 * 未经本公司许可，不得修改该源代码。
 * 在获得修改源代码授权的情况下不得将源代码提供给第三方公司使用，不得在互联网上传播该源代码。
 * http://www.blogmethods.com
 */
package cn.collin.commons.utils;

import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;

public class ImageUtils {

	public static BufferedImage getScaledInstance(BufferedImage img,
			int targetWidth, int targetHeight, int scale, Object hint,
			boolean higherQuality) {
		int type = !img.isAlphaPremultiplied() ? BufferedImage.TYPE_INT_RGB
				: BufferedImage.TYPE_INT_ARGB;
		BufferedImage ret = img;
		int w, h;
		if (higherQuality) {
			w = img.getWidth();
			h = img.getHeight();
		} else {
			w = targetWidth;
			h = targetHeight;
		}

		do {
			if (higherQuality && w > targetWidth) {
				w /= scale;
				if (w < targetWidth) {
					w = targetWidth;
				}
			}

			if (higherQuality && h > targetHeight) {
				h /= scale;
				if (h < targetHeight) {
					h = targetHeight;
				}
			}

			BufferedImage tmp = new BufferedImage(w, h, type);
			Graphics2D g2 = tmp.createGraphics();
			g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION, hint);
			g2.drawImage(ret, 0, 0, w, h, null);
			g2.dispose();

			ret = tmp;
		} while (w != targetWidth || h != targetHeight);

		return ret;
	}

	public static BufferedImage getSubImageAsSquare(BufferedImage img,
			int length) {
		int width = img.getWidth();
		int height = img.getHeight();
		BufferedImage temp = null;
		if (width > height && width > length) {
			temp = img.getSubimage((width - height) / 2, 0, height, height);
		} else if (width < height && height > length) {
			temp = img.getSubimage(0, (height - width) / 2, width, width);
		} else {
			temp = img;
		}
		return temp;
	}

	public static void generateSquareThumbnail(File image, int size,
			String filePath) throws IOException {
		BufferedImage bi = ImageIO.read(image);
		int width = bi.getWidth();
		// int height = bi.getHeight();
		BufferedImage temp = null;
		if (width > size) {
			temp = getSubImageAsSquare(bi, size);

			if (width > size) {
				int scale = 2;
				if (new Integer(width).doubleValue() / size > 10)
					scale = 8;
				temp = getScaledInstance(temp, size, size, scale,
						RenderingHints.VALUE_INTERPOLATION_BILINEAR, true);
			}
		} else {
			temp = bi;
		}
		ImageIO.write(temp, "png", new File(filePath));
	}
}
